package com.haven.webrobotserver.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.haven.webrobotserver.domain.Menu;
import com.haven.webrobotserver.domain.Menuitem;
import com.haven.webrobotserver.domain.User;
import com.haven.webrobotserver.service.MenuService;
import com.haven.webrobotserver.utils.List2JsonObjectTreeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@CrossOrigin(origins = "http://localhost:8080")
@RequestMapping("/menu")
public class MenuController {

    @Autowired(required = false)
    private MenuService menuService;

    @GetMapping("/getMenu")
    public JSONObject getMenu(){
        JSONObject jsonObject = new JSONObject();

        if(menuService == null){
            System.out.println("menuService instance in MenuController is null");
            return null;
        }

        List<Menuitem> menu =  menuService.getMenu();

        String s = JSON.toJSONString(menu);
        JSONArray jsonObjects = JSON.parseArray(s);

        JSONArray objects = List2JsonObjectTreeUtil.listToTree(jsonObjects, "id", "parent", "children");

        jsonObject.put("data",objects);
        jsonObject.put("status",200);
        jsonObject.put("msg","成功");
        return jsonObject;
    }

    @PostMapping("/getUserMenus")
    public JSONObject getUserMenus(@RequestBody User user){
        JSONObject result = new JSONObject();

        try{
            List<Menu> userMenus = menuService.getUserMenus(user);
            if(userMenus != null) {

                System.out.println(userMenus);

                String s = JSONObject.toJSONString(userMenus);
                JSONArray objects = JSONObject.parseArray(s);
                result.put("data", objects);
                result.put("status", 200);
            }
        }catch(Exception e){
            e.printStackTrace();
            result.put("status",500);
        }


        return result;
    }


}
